package qq2564874169.tuaotuao.fx;


public class LongId {
    /**
     * 起始的时间戳
     */
    private final static long START = 1480166465631L;
    /**
     * 每一部分占用的位数
     */
    //序列号占用的位数
    private final static long SEQUENCE_BIT = 12;
    //机器标识占用的位数
    private final static long MACHINE_BIT = 5;
    //数据中心占用的位数
    private final static long DATACENTER_BIT = 5;
    /**
     * 每一部分的最大值
     */
    public final static long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BIT);
    public final static long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);
    public final static long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);
    /**
     * 每一部分向左的位移
     */
    private final static long MACHINE_LEFT = SEQUENCE_BIT;
    private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;

    //数据中心
    private static long dataCenterId;
    //机器标识
    private static long machineId;
    //序列号
    private static long sequence = 0L;
    //上一次时间戳
    private static long lastTime = -1L;

    public static void set(int dataCenterId, int machineId) {
        if (dataCenterId > MAX_DATACENTER_NUM || dataCenterId < 0) {
            throw new RuntimeException("dataCenterId有效值：0 - " + MAX_DATACENTER_NUM);
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new RuntimeException("machineId有效值：0 - " + MAX_MACHINE_NUM);
        }
        LongId.dataCenterId = dataCenterId;
        LongId.machineId = machineId;
    }

    private static long getNext() {
        long mills = getNew();
        while (mills <= lastTime) {
            mills = getNew();
        }
        return mills;
    }

    private static long getNew() {
        return System.currentTimeMillis();
    }

    public static synchronized long newid() {
        long currstmp = getNew();
        while (currstmp < lastTime) {
            Task.delay(1000);
            currstmp = getNew();
        }

        if (currstmp == lastTime) {
            //相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currstmp = getNext();
            }
        } else {
            //不同毫秒内，序列号置为0
            sequence = 0L;
        }

        lastTime = currstmp;

        //时间戳部分<<数据中心部分<<机器标识部分<<序列号部分
        return (currstmp - START) << TIMESTMP_LEFT
                | dataCenterId << DATACENTER_LEFT
                | machineId << MACHINE_LEFT
                | sequence;
    }
}
